import React, { useRef, useState } from "react";
import { SearchBar } from "antd-mobile";
import { SearchBarRef } from "antd-mobile/es/components/search-bar";
import { useNavigate } from "react-router-dom";

import styles from "pages/Search/SearchDefault/styles.module.scss";
import { ReactComponent as DeleteIcon } from "assets/icons/icon-delete.svg";
import { useSearchs } from "hooks/todo/useSearchs";
import SearchItem from "components/SearchItem";

export default function SearchDefault() {
  const [searchContent, setSearchContent] = useState("");
  const searchRef = useRef<SearchBarRef>(null);
  const navigate = useNavigate();
  const { searchs, createSearch, clearSearchs } = useSearchs();

  const focus = () => {
    searchRef.current?.focus();
  };

  return (
    <div>
      <div className={styles.header}>
        <SearchBar
          ref={searchRef}
          placeholder="搜索"
          showCancelButton={() => true}
          value={searchContent}
          onChange={(value) => setSearchContent(value)}
          onSearch={() => {
            createSearch(searchContent.trim());
            navigate("/search/content?q=" + searchContent);
          }}
          style={{
            "--border-radius": "12px",
            "--background": "#EDEDED",
          }}
        />
      </div>
      {/* 最近搜索区域 */}
      {searchs.length === 0 ? (
        <></>
      ) : (
        <div className={styles.late}>
          <div className={styles.title}>
            最近搜索
            <DeleteIcon
              onClick={() => {
                clearSearchs();
              }}
            ></DeleteIcon>
          </div>
          <div className={styles.searchs}>
            {searchs.slice(0, 10).map((item) => (
              <SearchItem
                key={new Date().getTime() + Math.random().toString(36).slice(2)}
                content={item}
                setSearchContent={setSearchContent}
                focus={focus}
              ></SearchItem>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
